const { chromium } = require("playwright");
const express = require("express");
const fetch = require("node-fetch");

const apiKey = "7be6d900-d38c-4dcd-b2dd-45632a0266fc";
const host = process.env.AGENT_HOST || "localhost:8848";
const config = {
    headless: true, // support: true or false
    autoClose: true,
};
const query = new URLSearchParams({
    "x-api-key": apiKey,
    config: encodeURIComponent(JSON.stringify(config)),
});

const app = express();

function sleep(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}
app.get("/", async (req, res) => {
    res.send(
        `<h1>Welcome to NST Browser API</h1>
        <p>Use the endpoint <a href="/api">/api</a> to start a task.</p>
        <p>Example: <a href="/api?profileId=e1adca1c-2aa2-461b-9336-eb63f8c93dda&taskName=task001">/api?profileId=77adbce1-3b45-4ff8-a40a-8b2c6f33148e&taskName=task001</a></p>`
    );
});

app.get("/api", async (req, res) => {
    const _profileId = req.query.profileId || "e1adca1c-2aa2-461b-9336-eb63f8c93dda";
    console.log(_profileId)
    const _taskName = req.query.taskName || "task001";
    let browser = null;
    try {
        var task = require("./task-manager/" + _taskName);
        console.log("开始执行任务 %s", _taskName);
        // 1. 启动浏览器
        const response = await fetch(
            "http://" + host + "/api/v2/browsers/" + _profileId,
            {
                method: "post",
                headers: {
                    "Content-Type": "application/json",
                    "x-api-key": apiKey,
                },
            }
        );
        const data = await response.json();
        if (data.msg === "success") {
            console.log("启动浏览器 : %s 完成  ", JSON.stringify(data));
        } else {
            console.error("启动浏览器失败: ", JSON.stringify(data));
            res.status(500).json({
                error: "Failed to start browser: " + data.msg,
            });
            return;
        }

        await sleep(1000); // 等待浏览器启动

        // 2. 连接浏览器
        console.log("开始连接浏览器 %s", _profileId);
        const browserWSEndpoint = `ws://${host}/api/v2/connect/${_profileId}?${query.toString()}`;
        browser = await chromium.connectOverCDP(browserWSEndpoint, {
            slowMo: 1000,
        });

        await task.main(browser, _profileId);

        res.json({ message: "Task completed successfully" });
    } catch (error) {
        console.error("任务执行失败:", error);
        res.status(500).json({ error: "Task Error: " + error.message });
    } finally {
        console.log(
            "完成浏览器 %s 的任务 %s, 关闭浏览器",
            _profileId,
            _taskName
        );
        await browser.close();
    }
});

let server = app.listen(8888, "0.0.0.0", (err) => {
    if (err) {
        console.error("Error starting server:", err);
        return;
    }
    console.log(
        "Listening on PORT http://%s:%s",
        server.address().address,
        server.address().port
    );
});

// app.get("/image", async (req, res) => {
//     const browserWSEndpoint = `ws://${host}/api/v2/connect/${profileId}?${query.toString()}`;
//     console.log("browserWSEndpoint: ", browserWSEndpoint);
//     const browser = await chromium.connectOverCDP(browserWSEndpoint, {
//         slowMo: 1000,
//     });

//     const page = await browser.newPage();
//     await page.goto("https://nstbrowser.io");
//     const screenshot = await page.screenshot({
//         fullPage: false,
//     });
//     res.end(screenshot, "binary");
//     await page.close();
//     await browser.close();
// });
